import time
from fastapi import FastAPI, status
from starlette.requests import Request
from starlette.staticfiles import StaticFiles

from context import lifespan
from core.exception.exceptions import global_exception_handlers
from logger import log
from settings import SettingConfig
from api.routers.img_view import img_router
from api.routers.request_response_view import req_res_router
from api.routers.user_view import user_router
from api.routers.excetpion_view import ex_router

settings = SettingConfig.get_settings("development")

# 一些属性和 swagger-api 相关，如 title，version，可以使用  http://127.0.0.1:8070/docs#/ 访问
# exception_handlers: 配置异常处理
app = FastAPI(title=settings.app_name,
              version=settings.app_version,
              lifespan=lifespan,
              exception_handlers=global_exception_handlers)

# 挂载静态目录，以 /static 的，访问到 static目录, name 可随意取名
app.mount("/static", StaticFiles(directory="static"), name="my_static")


@app.middleware("http")
async def request_log_middleware(request: Request, call_next):
    """
    添加中间件
    :param request:
    :param call_next:
    :return:
    """
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    log.info('request URL:{0} ,method:{1},query_params:{2},cost time: {3:.3f}'
             .format(request.url.path, request.method,
                     request.query_params, process_time))
    return response


# 添加其它模块的router
app.include_router(user_router)
app.include_router(ex_router)
app.include_router(img_router)
app.include_router(req_res_router)


# 已过时,使用上面的 context.lifespan 方法
# @app.on_event("startup")
# async def startup():
#     """
#     启动时调用
#     :return:
#     """
#     print("on start....")
#
# 已过时,使用上面的 context.lifespan 方法
# @app.on_event("shutdown")
# async def shutdown():
#     """
#     停止服务时调用
#     :return:
#     """
#     print("on shutdown...")

@app.get("/")
async def root():
    return {"message": "Hello World"}


# status_code 设置响应状态码
@app.get("/hello/{name}", status_code=status.HTTP_200_OK)
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


if __name__ == '__main__':
    """
        使用 自定义方式
    """
    import uvicorn  # 导入容器库

    uvicorn.run(app, host='0.0.0.0', port=8000)
